// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()

  let targetCourse = event.course
  let db = cloud.database();
  let today = new Date()
  let sundayTimeStamp = today - today.getDay() * 24 * 3600 * 1000
  let sundayString = new Date(sundayTimeStamp).toLocaleDateString().replace(/\//g, '-')
  let res;
  const _ = db.command
  try {
    let r = await db.collection("tb_schedule").where({
        date: _.gt(sundayString),
        _openid: wxContext.OPENID
      })
      .orderBy('date', 'asc')
      .get()
    res = {}
    let list = r.data;
    list.forEach(t => {
      res[t.date] = t.self && t.self[targetCourse] && t.self[targetCourse].duration || 0
    })
  } catch (e) {}
  return res;
}